package com.gsbelarus.gedemin.salary.fragment.statistic;

import android.os.Bundle;
import android.support.v4.app.FragmentTransaction;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;

import com.gsbelarus.gedemin.lib.Utils;
import com.gsbelarus.gedemin.lib.ui.activity.drawer.SyncActivityDrawerModel;
import com.gsbelarus.gedemin.lib.ui.dialog.DatePickerDialog;
import com.gsbelarus.gedemin.lib.ui.fragment.FragmentModel;
import com.gsbelarus.gedemin.lib.ui.interfaces.OnDateSet;
import com.gsbelarus.gedemin.salary.R;
import com.gsbelarus.gedemin.salary.database.RealmHelper;
import com.gsbelarus.gedemin.salary.util.CurrencyHelper;
import com.gsbelarus.gedemin.salary.util.DateFormatHelper;

import java.util.Calendar;
import java.util.List;

import io.realm.Realm;

@SuppressWarnings("ALL")
public class StatisticDatesFragment extends FragmentModel implements
        View.OnClickListener, OnDateSet, CurrencyHelper.OnCurrencySwitcherChanged {

    private List<Calendar> dates;
    private DatePickerDialog dialog;
    private Calendar firstDate;
    private Calendar secondDate;

    private TextView firstDateButton;
    private TextView secondDateButton;

    private boolean isClickOnFirstDate;
    private NotifyDataChangedListener updater;

    private CurrencyHelper currencyHelper;
    private RealmHelper realmHelper;

    @Override
    public int getViewResource() {
        return R.layout.statistic_dates;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ((SyncActivityDrawerModel) getActivity()).showElevationToolbar(true);

        setHasOptionsMenu(true);
        setReloadViewByChangingOrientation(false);

        realmHelper = new RealmHelper(Realm.getInstance(context));
        currencyHelper = CurrencyHelper.getInstance(context);
        currencyHelper.addOnCurrencySwitcherChanged(this);

        FragmentTransaction transaction = getFragmentManager().beginTransaction();
        StatisticFragment fragment = new StatisticFragment();
        updater = fragment;
        transaction.replace(R.id.statistic_dates_content, fragment);
        transaction.commitAllowingStateLoss();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        currencyHelper.removeOnCurrencySwitcherChanged(this);
        realmHelper.getRealm().close();
    }

    @Override
    public void onCreateViewFragment(View rootView) {
        super.onCreateViewFragment(rootView);

        firstDateButton = (TextView) rootView.findViewById(R.id.statistic_dates_first_date_button);
        secondDateButton = (TextView) rootView.findViewById(R.id.statistic_dates_second_date_button);

        firstDateButton.setOnClickListener(this);
        secondDateButton.setOnClickListener(this);
    }

    @Override
    public void onChanged(CurrencyHelper.Kind kind) {
        Calendar[] dates = DateFormatHelper.getFixedDates(firstDate, secondDate);
        if (dates != null)
            notifyUpdater(dates[0], dates[1]);
    }

    @Override
    public void readDataBase() {
    }

    @Override
    public void initView(View view) {
        dates = realmHelper.getPayslipPossibleDatesList();
        if (dates == null) return;

        firstDate = dates.get(0);
        secondDate = dates.get(dates.size() - 1);

        /** отображаем данные на год */
        Calendar cal = (Calendar) secondDate.clone();
        cal.add(Calendar.MONTH, -11);
        if (firstDate.before(cal))
            firstDate = cal;


        dialog = new DatePickerDialog(getActivity(), dates, Calendar.MONTH);
        dialog.setOnDateSetListeners(this);

        if (dates.isEmpty()) return;
        choiceDate(firstDateButton, firstDate);
        choiceDate(secondDateButton, secondDate);

        Calendar[] fixedDates = DateFormatHelper.getFixedDates(firstDate, secondDate);
        if (fixedDates != null)
            notifyUpdater(fixedDates[0], fixedDates[1]);
    }

    @Override
    public void onClick(View view) {
        isClickOnFirstDate = (view == firstDateButton);

        if (isClickOnFirstDate) dialog.setDate(firstDate);
        else dialog.setDate(secondDate);
        dialog.show();
    }

    @Override
    public void updateDate(int day, int month, int year) {
        Calendar cal = Calendar.getInstance();
        cal.set(year, month - 1, day);
        if (isClickOnFirstDate) firstDate = cal;
        else secondDate = cal;

        choiceDate(firstDateButton, firstDate);
        choiceDate(secondDateButton, secondDate);

        Calendar[] dates = DateFormatHelper.getFixedDates(firstDate, secondDate);
        if (dates != null)
            notifyUpdater(dates[0], dates[1]);
    }

    private void choiceDate(TextView dateTextView, Calendar date) {
        dateTextView.setText(Utils.getShortMonthName(context, date.get(Calendar.MONTH)).toUpperCase() + " " + date.get(Calendar.YEAR));
    }

    private void notifyUpdater(Calendar firstDate, Calendar secondDate) {
        if (updater != null)
            updater.notifyDataChanged(firstDate, secondDate);
    }

    public interface NotifyDataChangedListener {

        /**
         * Вызывается если требуется обновить содержимое фрагмента.
         *
         * @param firstDate  первая дата "с"
         * @param secondDate вторая дата "по"
         */
        void notifyDataChanged(Calendar firstDate, Calendar secondDate);
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        super.onCreateOptionsMenu(menu, inflater);
        inflater.inflate(R.menu.currency_switcher, menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.action_currency_switch:
                currencyHelper.showChoiceDialog(getActivity(), null);
                break;
        }
        return super.onOptionsItemSelected(item);
    }
}
